import { Ref, computed } from 'vue'
// import { io, Socket } from 'socket.io-client'
// import { DefaultEventsMap } from 'socket.io-client/build/typed-events'
import { store } from '@/store'

// let socket: Socket<DefaultEventsMap, DefaultEventsMap>

export interface Log {
  level: number
  ts: string
  msg: string
}

const useSocket = (): Ref<Log[]> => {
  const func = (e: any) => {
    console.log(e && e.data)
  }

  // if (!socket) {
  //   socket = io(process.env.VUE_APP_SOCKET_IO || '')
  //   socket.on('connect', () => {
  //     console.log('socket connected')
  //   })

  //   socket.on('log', (e: Log) => {
  //     console.log(e)
  //     store.dispatch('app/addlog', e.data)
  //   })

  //   // 监听所有事件
  //   // socket.onAny((name, ...args) => {
  //   //   console.log(name)
  //   //   console.log(...args)
  //   // })

  //   socket.on('disconnect', () => {
  //     console.log(socket.id)
  //   })
  // }

  ;(window as any).rpa_log = (level: number, ts: string, msg: string) => {
    const log: Log = { level, ts, msg: decodeURIComponent(msg) }
    store.dispatch('app/addlog', log)
  }

  // onBeforeUnmount(() => {
  //   socket.off('onmessage', func)
  // })

  return computed(() => store.state.app.logs)
}

export default useSocket
